package com.tang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.reggie.common.Constant;
import com.tang.reggie.dto.DishDto;
import com.tang.reggie.mapper.DishMapper;
import com.tang.reggie.pojo.Category;
import com.tang.reggie.pojo.Dish;
import com.tang.reggie.pojo.DishFlavor;
import com.tang.reggie.service.CategoryService;
import com.tang.reggie.service.DishFlavorService;
import com.tang.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**Redis缓存*/
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品，因为要关联两张表，需要加上事务
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
        //保存dish表里的数据
        super.save(dishDto);

        //保存口味表数据
        //需要在每一行的口味数据中添加菜品id
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

/*        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key*/
        //删除指定分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

    }

    /**
     * 菜品展示
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<Dish> findDishWithCategoryName(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
        //排序条件
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        super.page(dishPage,dishLambdaQueryWrapper);

        List<Dish> records = dishPage.getRecords();
        for (Dish record : records) {
            Category category = categoryService.getById(record.getCategoryId());
            record.setCategoryName(category.getName());
        }
        return dishPage;
    }

    @Override
    public DishDto selectById(Long id) {
        //查询菜品基本信息
        Dish dish = super.getById(id);

        //查询出对应口味的信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(lqw);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithDishFlavors(DishDto dishDto) {
        //保存菜品基本信息
        super.updateById(dishDto);

        //删除口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);

        //增加口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

        /**
         * 注意: 在这里我们推荐使用第一种方式进行清理，这样逻辑更加严谨。
         * 因为对于修改操作，用户是可以修改菜品的分类的，如果用户修改了菜品的分类，那么原来分类下将少一个菜品，新的分类下将多一个菜品，
         * 这样的话，两个分类下的菜品列表数据都发生了变化
         */
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void delete(Long[] ids) {
        //先删除口味表里的数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            //获取选择菜品的分类id，然后删除指定分类下的缓存
            Dish dish = super.getById(id);
            //清理某个分类下面的菜品缓存数据,
            // 优化：停售状态的菜品删除，其实可以不影响缓存数据
            String key = "dish_" + dish.getCategoryId() + "_"+dish.getStatus();
            redisTemplate.delete(key);

            lqw.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(lqw);
            lqw.clear();//因为用的是同一个条件构造器，所以需要将之前操作成功后的条件去掉
            //删除菜单表里的数据
            super.removeById(id);
        }
    }

    /**
     * 状态修改
     * @param status
     * @param ids
     */
    @Override
    @Transactional
    public void updateStatus(int status, Long[] ids) {
        //根据id修改状态
        Dish dish = new Dish();
        dish.setStatus(status);
        for (Long id : ids) {
            //获取选择菜品的分类id，然后删除指定分类下的缓存
            Dish dish1 = super.getById(id);
            //清理某个分类下面的菜品缓存数据
            String key = "dish_" + dish1.getCategoryId() + "_1";
            redisTemplate.delete(key);

            dish.setId(id);
            super.updateById(dish);
        }
    }

    /**
     * 根据分类id查询菜品信息
     * @param dishDto
     * @return
     */
    @Override
    public List<DishDto> getByCategory(DishDto dishDto) {
        List<DishDto> dishDtoList=null;
        //动态生成出Redis的key
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();////dish_XXXXXXXXXXXXXX_1
        //查询缓存中是否有菜品数据
        dishDtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);
        //判断是否有数据，有就直接返回
        if (dishDtoList!=null) {
            return dishDtoList;
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getStatus, Constant.ENNABLE_CODE);
        dishLambdaQueryWrapper.eq(dishDto.getCategoryId() != null,Dish::getCategoryId, dishDto.getCategoryId());
        String name = dishDto.getName();
        if (StringUtils.isNotBlank(name)){
            name=name.trim();
            dishLambdaQueryWrapper.like(name!="",Dish::getName,name);
        }
        List<Dish> list = super.list(dishLambdaQueryWrapper);

        dishDtoList=list.stream().map(dish -> {
            DishDto dishDto1 = new DishDto();
            BeanUtils.copyProperties(dish,dishDto1);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category!=null){
                dishDto1.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> flqw = new LambdaQueryWrapper<>();
            flqw.eq(dish.getId()!=null,DishFlavor::getDishId,dish.getId());
            //select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavors = dishFlavorService.list(flqw);
            dishDto1.setFlavors(dishFlavors);
            return dishDto1;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis,并设置过期时间为1小时
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return dishDtoList;
    }
}
